import type { LoginParams } from "@/api/user"

import { ref, reactive, computed } from 'vue'
import { defineStore } from 'pinia'

import { doUserLoginAPI } from "@/api/user"


interface UserParamsInfo {
    token?: string;
    userid?: string;
}

export const useUserStore = defineStore('user', () => {

    // state
    const userInfo: any = reactive<UserParamsInfo>({
        token: "",
        userid: "",
    })
    const a = ref(1);
    const b = ref(2);

    // 计算属性
    const token = computed(() => {
        return userInfo.token;
    })

    const userid = computed(() => {
        return userInfo.userid;
    })

    const isLogin = computed(() => {
        return userInfo.token && userInfo.userid ? true : false;
    })


    const updateUserInfo = (payload: UserParamsInfo) => {
        for (const key in (payload as UserParamsInfo)) {
            userInfo[key] = (payload as any)[key];
        }
    }

    const LoginAndUpdateUserInfo = (payload: LoginParams): Promise<any> => {
        return doUserLoginAPI(payload).then((res) => {
            updateUserInfo(res.data);
        })
    }

    const exitAndUpdateUserInfo = (): void => {
        updateUserInfo({
            token: "",
            userid: "",
        });
    }

    return { a, b, userInfo, token, userid, isLogin, updateUserInfo, LoginAndUpdateUserInfo, exitAndUpdateUserInfo }
}, {
    // 默认将模块中的state数据存储到localStorage中  (将所有state数据整合到一个对象中 {userInfo:{token,userid}}=>转JSON字符串)
    persist: true,  // 默认=> 将所有state数据整合到一个对象中存储

    // persist: {
    //     key: "Auth", // 如果没有指定key (默认 store名称作为键名)
    //     paths: ["a", "userInfo.token"],  // 可以指定哪些数据被存储(默认存储所有)
    //     storage: sessionStorage,  // 修改存储数据的方法 (localStorage(默认)  sessionStorage)
    // }

})
